﻿using System;
using Abp.AspNetCore.Mvc.Results.Wrapping;
using Abp.Runtime;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

namespace Magicodes.AppSession
{
    public class AppTenantManager : IAppTenantManager
    {
        public IHttpContextAccessor HttpContextAccessor { get; set; }
        public const string SessionOverrideContextKey = "Abp.Runtime.Session.AppTenantManager.Override";
        public IAmbientScopeProvider<int?> SessionOverrideScopeProvider { get; set; }

        protected int? OverridedValue => SessionOverrideScopeProvider?.GetValue(SessionOverrideContextKey);

        public void Initialize()
        {
        }

        public int? GetTenantId()
        {
            if (OverridedValue != null)
            {
                return OverridedValue;
            }
            if (HttpContextAccessor == null) return null;
            var context = HttpContextAccessor.HttpContext;
            //租户Id
            int? tenantId = null;

            #region 获取请求参数中的租户Id
            if (!string.IsNullOrWhiteSpace(context.Request.Query["TenantId"]))
            {
                tenantId = Convert.ToInt32((string)context.Request.Query["TenantId"]);
            }
            else if (!string.IsNullOrWhiteSpace(context.Request.Query["TKey"]))
            {
                tenantId = Convert.ToInt32((string)context.Request.Query["TKey"]);
            }
            else
            {
                var routeContext = new RouteContext(context);
                tenantId = routeContext.RouteData.Values["TenantId"] != null
                    ? Convert.ToInt32(routeContext.RouteData.Values["TenantId"])
                    : (int?)null;

            }
            #endregion
            return tenantId;
        }
    }
}